package cn.xxstudy.blog.controller.admin

import cn.xxstudy.blog.bean.BlogQuery
import cn.xxstudy.blog.bean.Msg
import cn.xxstudy.blog.entity.Blog
import cn.xxstudy.blog.entity.User
import cn.xxstudy.blog.service.BlogService
import cn.xxstudy.blog.service.CategoryService
import cn.xxstudy.blog.service.CommentService
import cn.xxstudy.blog.service.TagsService
import cn.xxstudy.blog.util.logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.web.PageableDefault
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.servlet.mvc.support.RedirectAttributes
import java.io.File
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession

/**
 * 作者：wuxinxi on 2020/11/25
 * 包名：cn.xxstudy.blog.controller.admin
 * TODO:博客管理
 */
@Controller
@RequestMapping("/admin")
class ManagerBlogController {
    @Autowired
    private lateinit var blogService: BlogService

    @Autowired
    private lateinit var categoryService: CategoryService

    @Autowired
    private lateinit var tagsService: TagsService

    @Autowired
    private lateinit var commentService: CommentService

    companion object {
        private const val MANAGE_BLOG_LIST = "admin/manager-blog-list"
        private const val MANAGE_BLOG_EDIT = "admin/manager-blog-edit"
        private const val REDIRECT_LIST = "redirect:/admin/blogs"
        private const val MANAGER_BLOG_LIST_FRAGMENT = "$MANAGE_BLOG_LIST :: blogList"
    }

    /**
     * 管理-博客-列表
     */
    @GetMapping("/blogs")
    fun blogs(@PageableDefault(size = 8, sort = ["updateDateTime"], direction = Sort.Direction.DESC) pageable: Pageable,
              query: BlogQuery, model: Model): String {
        model.addAttribute("categoryList", categoryService.listCategory())
        model.addAttribute("blogPage", blogService.listBlog(true,pageable, query))
        return MANAGE_BLOG_LIST
    }

    /**
     * 新建博客
     */
    @GetMapping("/blog/create")
    fun blogCreate(model: Model): String {
        model.addAttribute("blog", Blog())
        setCategoryAndTags(model)
        return MANAGE_BLOG_EDIT
    }

    /**
     * 编辑/修改博客
     */
    @GetMapping("/blog/{id}/edit")
    fun blogEdit(@PathVariable id: Long, redirectAttributes: RedirectAttributes, model: Model): String {
        setCategoryAndTags(model)
        val blog = blogService.getBlog(true,id)
        if (blog == null) {
            redirectAttributes.addFlashAttribute("msg", Msg(false, "博客走丢了..."))
            return REDIRECT_LIST
        }
        blog.initTagsFormat()
        model.addAttribute("blog", blog)
        return MANAGE_BLOG_EDIT
    }

    /**
     * 博客搜索
     */
    @PostMapping("/blogs/search")
    fun searchBlog(@PageableDefault(size = 8, sort = ["updateDateTime"], direction = Sort.Direction.DESC) pageable: Pageable,
                   query: BlogQuery, model: Model): String {
        model.addAttribute("blogPage", blogService.listBlog(true,pageable, query))
        return MANAGER_BLOG_LIST_FRAGMENT
    }

    /**
     * 存储/修改博客
     */
    @PostMapping("/blogs")
    fun blogSavePost(blog: Blog, redirectAttributes: RedirectAttributes, session: HttpSession): String {
        blog.user = session.getAttribute("user") as User
        blog.category = categoryService.getCategoryById(blog.category.id)
        blog.tags = tagsService.listTags(blog.tagIds)
        val newBlog = if (blog.id == null) {
            blogService.saveBlog(blog)
        } else {
            blogService.updateBlog(blog.id, blog)
        }

        redirectAttributes.addFlashAttribute("msg",
                if (newBlog == null) Msg(false, "${blog.title} 保存失败")
                else Msg(true, "${blog.title} 保存成功"))
        return REDIRECT_LIST
    }


    /**
     * 删除博客
     */
    @GetMapping("/blog/{id}/delete")
    fun deleteBlog(@PathVariable id: Long, redirectAttributes: RedirectAttributes): String {
        commentService.deleteCommentByBlogId(id)
        val res = blogService.deleteBlog(id)
        redirectAttributes.addFlashAttribute("msg", if (res) Msg(true, "博客删除成功") else Msg(false, "博客删除失败"))
        return REDIRECT_LIST
    }


    private fun setCategoryAndTags(model: Model) {
        model.addAttribute("categoryList", categoryService.listCategory())
        model.addAttribute("tagList", tagsService.listTags())
    }
}